<template>
    <div>
        <Row :gutter="16">
            <Col span="6" >
                <Card class="hiddenscroll" style="height: 80vh;overflow:auto;border-radius:15px;">
                    <p slot="title">
                        <Icon type="ios-film-outline"></Icon>
                        权限树
                    </p>
                    <Tree ref="UserTree" :data="AuthorizeTree" show-checkbox></Tree>
                </Card>
                
            </Col>
            <Col span="18">
                <Card class="hiddenscroll" style="height: 80vh;overflow:auto;border-radius:15px;">
                    <p slot="title">
                        <Icon type="ios-film-outline"></Icon>
                        人员信息
                    </p>
                    <Row class="hiddenscroll" style="height:65vh;">
                        <Col span="22" offset="1">
                            <Form ref="User" :model="User" :rules="ruleValidate" :label-width="80" :style="{marginTop: '30px'}">
                                <Row>
                                    <Col span="10" offset="2">
                                        <FormItem label="人员编码">
                                            <Input v-model.trim="User.NumCode" readonly placeholder="人员编码由系统自动生成" ></Input>
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row>
                                    <Col span="10" offset="2">
                                        <FormItem label="用户名" prop="UserName">
                                            <Input v-model.trim="User.UserName"  placeholder="用户名" ></Input>
                                        </FormItem>
                                    </Col>
                                    <Col span="10" >
                                        <FormItem label="姓名" prop="RealName">
                                            <Input v-model.trim="User.RealName" placeholder="姓名" ></Input>
                                        </FormItem>
                                    </Col>
                                </Row>
                                
                                <Row v-if="User.Id === '00000000-0000-0000-0000-000000000000'" >
                                    <Col span="10" offset="2">
                                        <FormItem label="新建密码" prop="Password">
                                            <Input v-model.trim="User.Password" type="password"  placeholder="新建密码" ></Input>
                                        </FormItem>
                                    </Col>
                                    <Col span="10" >
                                        <FormItem label="确认密码" prop="PwdCheck">
                                            <Input v-model.trim="ConfirmPassword" type="password" placeholder="确认密码" ></Input>
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row>
                                    <Col span="10" offset="2">
                                        <FormItem label="角色编号（默认）">
                                            <Input readonly v-model.trim="User.CurrentPlayRole.NumCode" placeholder="由系统调取获得" ></Input>
                                        </FormItem>
                                    </Col>
                                    <Col span="10">
                                        <FormItem label="角色名称（默认）">
                                            <Input readonly v-model.trim="User.CurrentPlayRole.Name" placeholder="例如：管理员" >
                                                <Button slot="append" @click="ShowDialog = true" icon="ios-search"></Button>
                                            </Input>
                                        </FormItem>
                                    </Col>
                                    <Modal
                                        v-model="ShowDialog"
                                        height="600vh"
                                        width="1000vh"
                                        ok-text="选择"
                                        @on-ok = "SelectRoles"
                                        cancel-text="关闭"
                                        title="请选择人员角色">
                                        <Row :gutter="16">
                                            <Col span="18" >
                                                <Card>
                                                    <p slot="title" style="height:32px;">
                                                        <Icon type="ios-ionitron-outline"></Icon>
                                                        角色列表
                                                        <Input suffix="ios-search" placeholder="请输入查询角色！" :style="{width: 'auto',float: 'right',borderRadius : '15px'}" :clearable="true" :search="true" />
                                                    </p>
                                                    <Table stripe highlight-row height="350vh" @on-row-click="SelectSingleRow" :columns="RoleColumns" :data="RoleData"></Table>
                                                    <div :style="{ background: 'white',padding: '15px 10px 10px',textAlign: 'center',marginRight: '135px'}">
                                                        <Page 
                                                            :style="{ textAlign:'right',marginTop: '0px',paddingRight: '0px',background: 'white'}"
                                                            show-sizer 
                                                            show-elevator 
                                                            show-total 
                                                            :total="RoleTotal"
                                                            :page-size="RolePageSize"
                                                            :page-size-opts="RolePageSizeOpts"
                                                            @on-change="RoleChangePage"
                                                            @on-page-size-change="RoleChangePageSize"/>
                                                    </div>
                                                </Card>
                                            </Col>
                                            <Col span="6">
                                                <Card  >
                                                    <p slot="title">
                                                        <Icon type="md-images" />
                                                        角色权限预览
                                                    </p>
                                                    <div class="hiddenscroll" style="height: 43.2vh;overflow:auto;border-radius:15px;">
                                                        <Tree disable :data="AuthorizeTree" show-checkbox></Tree>
                                                    </div>
                                                </Card>
                                            </Col>
                                        </Row>
                                        
                                    </Modal>
                                </Row>
                                <Row>
                                    <Col span="10" offset="2">
                                        <FormItem label="启用标记">
                                            <div style="text-align:center">
                                                <RadioGroup v-model.number="User.IsUsed" >
                                                    <Radio :label="1" >启用</Radio>
                                                    <Radio :label="0" >禁用</Radio>
                                                </RadioGroup>
                                            </div>
                                        </FormItem>
                                    </Col>
                                </Row>
                            </Form>
                        </Col>
                    </Row>
                </Card>
            </Col>
        </Row>
        <Row>
            <Col span="20" offset="2" style="text-align:center;margin-top:48px">
                <Button type="primary" @click="Submit('User')">提交</Button>
                <Button @click="Reset('User')" style="margin-left: 108px">重置</Button>
            </Col>
        </Row>
    </div>
    
</template>

<script>
import { mapState } from "vuex";
import { CreateCode,GetOne,Create,Update,GetAllAuthorizes } from '@/axios/api/UsersAPI'
import { GetListByPage } from '@/axios/api/RolesAPI'

export default {
    computed:{
        ...mapState('users',[
            'currentUserID',
            'pageIndex',
            'pageSize',
        ])
    },
    components: {
        
    },
    mounted: function(){
        if(this.currentUserID != ''){
            this.$Spin.show();
        }
        setTimeout(() => {
            this.$Spin.hide();
        }, 1000);

        GetListByPage({
            PageIndex: this.RolePageIndex,
            PageSize: this.RolePageSize
        }).then(res => {
            this.RoleTotal = res.totalCount;
            this.RoleData = res.items
        })
        
        if(this.currentUserID != ''){
            
            GetOne(this.currentUserID).then(res => {

                this.User.Id = res.Id;
                this.User.Num = res.Num;
                this.User.NumCode = res.NumCode;
                this.User.UserName = res.UserName;
                this.User.RealName = res.RealName;
                this.User.Password = res.Password;
                this.User.IsUsed = res.IsUsed;
                this.User.AuthorizeTree = res.AuthorizeTree;

                if(res.CurrentPlayRole){
                    this.User.CurrentPlayRole = res.CurrentPlayRole;
                }

                if(res.AuthorizeTree){
                    this.AuthorizeTree = JSON.parse(res.AuthorizeTree);
                }
                this.User.CreateTime = res.CreateTime;
            });
        }
        else{
            CreateCode().then(res => {
                this.User.NumCode = res.toString();
            })
            GetAllAuthorizes().then(authorizeres => {
                this.AuthorizeTree = authorizeres;
            })
        }
    },
    watch: {
        'ConfirmPassword'(){
            this.$refs.User.validateField('PwdCheck');
        }
    },
    data () {
        const ValidatePassword = (rule,value,callback) => {
            console.log(value);
            if (value === '') {
                callback(new Error('请输入您的密码！'));
            } else {
                if (this.ConfirmPassword !== '') {
                    // 对第二个密码框单独验证
                    this.$refs.User.validateField('PwdCheck');
                }
                callback();
            }
        };
        const ValidatePwdCheck = (rule,value,callback) => {
             if (this.ConfirmPassword === '') {
                callback(new Error('请再次输入您的密码！'));
            } else if (this.ConfirmPassword !== this.User.Password) {
                callback(new Error('两次密码输入无法匹配！'));
            } else {
                callback();
            }
        };
        return {
            ShowDialog: false,
            User:{
                Id: '00000000-0000-0000-0000-000000000000',
                Num: 0,
                NumCode: '',
                UserName: '',
                Password: '',
                RealName: '',
                CurrentPlayRole: {
                    Id: '00000000-0000-0000-0000-000000000000',
                    NumCode: '',
                    Name: '',
                },
                IsUsed: 1,
                AuthorizeTree: '',
                CreateTime: new Date()
            },
            ruleValidate: {
                UserName: [{ required: true, message: '账户名称为必填项！', trigger: 'blur'  }],
                RealName: [{ required: true, message: '真实姓名为必填项！', trigger: 'blur'  }],
                Password: [{ validator: ValidatePassword, trigger: 'blur'  }],
                PwdCheck: [{ validator: ValidatePwdCheck, trigger: 'blur'  }]
            },
            AuthorizeTree: [],
            ConfirmPassword: '',
            RoleColumns: [
                 {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    type: 'index',
                    title: '序号',
                    width: 80,
                    align: 'center'
                },
                {
                    title: '角色编码',
                    key: 'NumCode',
                    align: 'center'
                },
                {
                    title: '角色名称',
                    key: 'Name',
                    align: 'center'
                }
            ],
            SelectedSingleRole:{
                Id:'00000000-0000-0000-0000-000000000000',
                Code: '',
                Name: ''
            },
            RoleData: [],
            PriviewAuthorizeTree:[],
            RoleTotal: 0,
            RolePageIndex: 1,
            RolePageSize: 10,
            RolePageSizeOpts: [10,25,50,100]
        };
    },
    methods:{
        Submit (name){
            //this.$Message.success('按了OK键');
             this.$refs[name].validate((valid) => {

                if (valid) {
                    if(this.User.Id == '00000000-0000-0000-0000-000000000000'){

                        this.$Message.success('校验通过!');

                        this.User.AuthorizeTree = JSON.stringify(this.GetUserTreeNodes()) ;

                        Create(this.User).then(res => {

                            if(res > 0){

                                setTimeout(() => {

                                    this.$store.dispatch('users/UpdateTableAsync',{
                                        PageIndex: this.pageIndex,
                                        PageSize: this.pageSize
                                    });

                                     this.$Notice.success({
                                        title: '操作提示',
                                        desc: '保存成功！ '
                                    });

                                }, 1000)
                               
                            }
                            else{

                                this.$Notice.error({
                                    title: '操作提示',
                                    desc: '保存失败！ '
                                });

                            }
                        }).catch(err =>{

                            this.$Notice.error({
                                title: '操作提示',
                                desc: '保存失败：' + err + '!'
                            });

                        })
                        
                    }
                    else{

                        this.$Message.success('校验通过!');

                        this.User.AuthorizeTree = JSON.stringify(this.GetUserTreeNodes()) ;

                        Update(this.User).then(res => {
                            if(res > 0){
                                setTimeout(() => {
                                    this.$store.dispatch('users/UpdateTableAsync',{
                                        PageIndex: this.pageIndex,
                                        PageSize: this.pageSize
                                    });

                                     this.$Notice.success({
                                        title: '操作提示',
                                        desc: '更新成功！'
                                    });
                                }, 1000)
                            }
                            else{
                                this.$Notice.success({
                                    title: '操作提示',
                                    desc: '更新失败！'
                                });
                            }
                        }).catch(err =>{
                            this.$Notice.error({
                                title: '操作提示',
                                desc: '更新失败：' + err.data + '!'
                            });
                        })
                    }
                    this.ChangeModal();
                } else {
                    this.$Message.error('校验失败!');
                    //this.ChangeModal('User');
                }
            })
            
        },
        Reset (name){
            this.$refs[name].resetFields();
        },
        GetUserTreeNodes(){

            var SelectNodes = this.$refs.UserTree.getCheckedAndIndeterminateNodes();
            
            SelectNodes = SelectNodes.filter(item => item.children);

            var EmptyNodes = this.AuthorizeTree.filter(item => item.children);

            SelectNodes.forEach(item => {
                EmptyNodes.splice(SelectNodes.indexOf(i => i.id=item.id),1)
            });

            var result = SelectNodes.concat(EmptyNodes);

            return result;
        },
        ChangeModal (){
            //this.$refs[name].resetFields();
            this.$store.commit('users/CHANGE_MODAL');
            this.$router.push('/system/users')
        },
        RoleChangePage(){

        },
        RoleChangePageSize(){

        },
        SelectRoles(){
            this.User.CurrentPlayRole.Id = this.SelectedSingleRole.Id;
            this.User.CurrentPlayRole.NumCode = this.SelectedSingleRole.NumCode;
            this.User.CurrentPlayRole.Name = this.SelectedSingleRole.Name;
        },
        SelectSingleRow(SelectedRole){
            this.SelectedSingleRole.Id = SelectedRole.Id;
            this.SelectedSingleRole.NumCode = SelectedRole.NumCode;
            this.SelectedSingleRole.Name = SelectedRole.Name;
        }
    }
}
</script>

<style scoped>
    .hiddenscroll::-webkit-scrollbar { width: 0 !important }
    .hiddenscroll { -ms-overflow-style: none; }
    .hiddenscroll { overflow: -moz-scrollbars-none; }
</style>